import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { useParams } from 'react-router-dom'
import { useRequest } from 'ahooks'
import { itemDetailsDataAPI } from '@/server/question'
import { changeSelected, restComponent } from '@/store/componentsReducer'
/**
 *  获取问卷详细信息
 */
const useLoadQuestionData = () => {
  const dispatch = useDispatch()
  const { id = '' } = useParams()
  const { loading, data, run } = useRequest(
    async () => {
      if (!id) throw new Error('没有id!')
      const { data } = await itemDetailsDataAPI(id)
      return data
    },
    {
      manual: true,
    }
  )
  useEffect(() => {
    if (data) {
      dispatch(restComponent(data.componentList))
      if (data.componentList.length > 0) {
        dispatch(changeSelected(data.componentList[0].fe_id!))
      }
    }
  }, [data, dispatch])
  useEffect(() => {
    run()
  }, [id, run])
  return { loading }
}

export default useLoadQuestionData
